from fastapi import APIRouter, Query,UploadFile,Request
from tortoise.expressions import Q

from app.controllers.appointment.category import category_controller
from app.controllers.appointment.project import appointment_project_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.appointment import *
from app.settings import settings
from app.core.redis_base import delete_keys
from app.models.appointment import AppointmentCategory
from app.utils.upload import upload_image

appointment_project_router = APIRouter()
model_name = "预约项目"


@appointment_project_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    total, data = await appointment_project_controller.do_list(page=page, page_size=page_size, search=q)
    category_objs = await appointment_project_controller.categorys()
    for item in data:
        item["type_name"] = category_objs[item["type"]]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@appointment_project_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await appointment_project_controller.do_detail(data_id=data_id)
    return Success(data=data)

@appointment_project_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        request: Request,
        data_in: AppointmentProjectCreate,
):
    await appointment_project_controller.do_create(request,obj_in=data_in)
    return Success(msg="创建成功")

@appointment_project_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        request: Request,
        data_in: AppointmentProjectUpdate,
):
    await appointment_project_controller.do_update(request,obj_in=data_in)
    return Success(msg="更新成功")

@appointment_project_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        request: Request,
        data_id: int = Query(..., description="ID"),
):
    await appointment_project_controller.do_delete(request,data_id=data_id)
    return Success(msg="删除成功")

# @appointment_project_router.get("/project", summary="获取项目分类")
# async def list_level():
#     level_objs = settings.APPOINTMENT_PROJECT
#     data = []
#     key = 0
#     for level in level_objs:
#         if level:
#             data.append({"label":level,"value":key})
#         key += 1
#     return Success(data=data)

@appointment_project_router.get("/project", summary="树形分类")
async def tree_dept():
    data = await category_controller.get_tree()
    datas = [{
        "id": 0,
        "name": "全部",
        "desc": "全部",
        "order": 1,
        "parent_id": -1,
        "children": data,  # 递归构建子部门
    }]
    return SuccessExtra(data=datas)

@appointment_project_router.get("/tree", summary="获取项目配置树")
async def list_tree():
    level_objs = await AppointmentCategory.filter(parent_id__gt=0).all().values()
    data = []
    key = 0
    for level in level_objs:
        if level["id"]:
            children = await appointment_project_controller.level_list(type=level["id"])
            data.append({"label":level["name"],"value":key+10000,"children":children})
        key += 1
    return Success(data=data)

@appointment_project_router.post("/file", summary="上传图片")
async def do_file(file: UploadFile):
    url = await upload_image(file,"appointment/project")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)